import React, { useState, useEffect, useRef } from "react";
import {
  Card,
  Table,
  Button,
  Space,
  Input,
  Form,
  Switch,
  Tag,
  Modal,
  Select,
  message,
  Popconfirm,
  Tooltip,
  Divider,
  Row,
  Col,
} from "antd";
import {
  SearchOutlined,
  DeleteOutlined,
  TagsOutlined,
  PlusOutlined,
} from "@ant-design/icons";
import type { ColumnsType } from "antd/es/table";
import { auth } from "@/utils/auth";
import moment from "moment";
import type { InputRef } from "antd";

interface ContentData {
  id: string;
  title: string;
  isApproved: boolean;
  recommendReason: string;
  tags: TagData[];
  channel: "小红书" | "朋友圈";
  createdAt: string;
  body: string;
  attachments: AttachmentData[];
}

interface TagData {
  id: string;
  name: string;
}

interface AttachmentData {
  id: string;
  fileUrl: string;
}

interface PaginationData {
  total: number;
  page: number;
  pageSize: number;
}

const ContentPage: React.FC = () => {
  const [searchForm] = Form.useForm();
  const [editTagsForm] = Form.useForm();
  const [isTagModalVisible, setIsTagModalVisible] = useState(false);
  const [currentRecord, setCurrentRecord] = useState<ContentData | null>(null);
  const [loading, setLoading] = useState(false);
  const [data, setData] = useState<ContentData[]>([]);
  const [tags, setTags] = useState<TagData[]>([]);
  const [tagname, setTagname] = useState("");
  const [pagination, setPagination] = useState<PaginationData>({
    total: 0,
    page: 1,
    pageSize: 10,
  });
  const [searchParams, setSearchParams] = useState({
    title: "",
    tagIds: [],
  });
  const inputRef = useRef<InputRef>(null);
  // 创建新标签
  const handleCreateTag = async () => {
    try {
      const isTokenValid = await auth.handleTokenExpiration();
      if (!isTokenValid) return;

      const response = await fetch("/agentapi/tags", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          Authorization: `Bearer ${await auth.getValidAccessToken()}`,
        },
        body: JSON.stringify({ name: tagname }),
      });

      if (response.status === 201) {
        const result = await response.json();
        setTags([...tags, result]);
        setTagname("");
        message.success("标签创建成功");
      } else {
        message.error("标签创建失败");
      }
    } catch (error) {
      message.error("标签创建失败，请检查网络连接");
    }
  };

  // 获取标签列表
  const fetchTags = async () => {
    try {
      const isTokenValid = await auth.handleTokenExpiration();
      if (!isTokenValid) return;

      const response = await fetch("/agentapi/tags", {
        headers: {
          Authorization: `Bearer ${await auth.getValidAccessToken()}`,
        },
      });

      if (response.status === 200) {
        const result = await response.json();
        setTags(result.data);
      } else {
        message.error("获取标签列表失败");
      }
    } catch (error) {
      message.error("获取标签列表失败，请检查网络连接");
    }
  };

  // 获取文案列表
  const fetchContents = async (page: number = pagination.page) => {
    try {
      setLoading(true);
      const isTokenValid = await auth.handleTokenExpiration();
      if (!isTokenValid) return;

      const queryParams = new URLSearchParams({
        page: page.toString(),
        pageSize: pagination.pageSize.toString(),
        title: searchParams.title,
        tagIds: searchParams.tagIds.join(","),
      });

      const response = await fetch(
        `/agentapi/contents?${queryParams.toString()}`,
        {
          headers: {
            Authorization: `Bearer ${await auth.getValidAccessToken()}`,
          },
        }
      );

      if (response.status === 200) {
        const result = await response.json();
        setData(result.data);
        setPagination({
          page: page,
          pageSize: pagination.pageSize,
          total: result.pagination?.total || 0,
        });
      } else {
        message.error("获取文案列表失败");
      }
    } catch (error) {
      message.error("获取文案列表失败，请检查网络连接");
    } finally {
      setLoading(false);
    }
  };

  // 首次加载和分页变化时获取数据
  useEffect(() => {
    fetchContents(1);
  }, [searchParams]);

  // 首次加载时获取标签数据
  useEffect(() => {
    fetchTags();
  }, []);

  const handleDelete = async (record: ContentData) => {
    try {
      const isTokenValid = await auth.handleTokenExpiration();
      if (!isTokenValid) return;

      const response = await fetch(`/agentapi/contents/${record.id}`, {
        method: "DELETE",
        headers: {
          Authorization: `Bearer ${await auth.getValidAccessToken()}`,
        },
      });

      if (response.status === 204) {
        message.success("删除成功");
        // 重新加载当前页数据
        fetchContents();
      } else {
        message.error("删除失败");
      }
    } catch (error) {
      message.error("删除失败，请检查网络连接");
    }
  };

  const handleStatusChange = async (checked: boolean, record: ContentData) => {
    try {
      const isTokenValid = await auth.handleTokenExpiration();
      if (!isTokenValid) return;

      const response = await fetch(
        `/agentapi/contents/${record.id}/${checked ? "approve" : "unapprove"}`,
        {
          method: "PATCH",
          headers: {
            "Content-Type": "application/json",
            Authorization: `Bearer ${await auth.getValidAccessToken()}`,
          },
        }
      );

      if (response.status === 200) {
        setData(
          data.map((item) =>
            item.id === record.id ? { ...item, isApproved: checked } : item
          )
        );
        message.success(`状态更新成功`);
      } else {
        message.error(`状态更新失败`);
      }
    } catch (error) {
      message.error(`状态更新失败，请检查网络连接`);
    }
  };

  const showTagModal = (record: ContentData) => {
    setCurrentRecord({ ...record, body: record.body.replace(/\\n/g, "\n") });
    editTagsForm.setFieldsValue({
      tags: record.tags.map((tag) => tag.id),
      recommendReason: record.recommendReason,
    });
    setIsTagModalVisible(true);
  };

  const handleTagsCancel = () => {
    setIsTagModalVisible(false);
    editTagsForm.resetFields();
    setCurrentRecord(null);
  };

  const handleTagsSave = async () => {
    try {
      const isTokenValid = await auth.handleTokenExpiration();
      if (!isTokenValid) return;

      const values = await editTagsForm.validateFields();
      if (currentRecord) {
        const response = await fetch(`/agentapi/contents/${currentRecord.id}`, {
          method: "PUT",
          headers: {
            "Content-Type": "application/json",
            Authorization: `Bearer ${await auth.getValidAccessToken()}`,
          },
          body: JSON.stringify({
            recommendReason: values.recommendReason,
            tagIds: values.tags,
          }),
        });

        if (response.status === 200) {
          message.success("更新成功");
          setIsTagModalVisible(false);
          editTagsForm.resetFields();
          setCurrentRecord(null);
          fetchContents();
        } else {
          message.error("更新失败");
        }
      }
    } catch (error) {
      message.error("更新失败");
    }
  };

  const columns: ColumnsType<ContentData> = [
    {
      title: "标题",
      dataIndex: "title",
      key: "title",
      ellipsis: {
        showTitle: false,
      },
      render: (title) => (
        <Tooltip placement="topLeft" title={title}>
          {title}
        </Tooltip>
      ),
    },
    {
      title: "状态",
      key: "status",
      render: (_, record) => (
        <div style={{ display: "flex", alignItems: "center" }}>
          <Switch
            checked={record.isApproved}
            onChange={(checked) => handleStatusChange(checked, record)}
          />
          <span style={{ marginLeft: 8 }}>
            {record.isApproved ? "通过" : "未通过"}
          </span>
        </div>
      ),
    },
    {
      title: "推荐理由",
      dataIndex: "recommendReason",
      key: "recommendReason",
      ellipsis: {
        showTitle: false,
      },
      render: (recommendReason) => (
        <Tooltip placement="topLeft" title={recommendReason}>
          {recommendReason}
        </Tooltip>
      ),
    },
    {
      title: "标签",
      key: "tags",
      render: (_, record) => (
        <Space size={[0, 8]} wrap>
          {record.tags.map((tag) => {
            return (
              <Tag color="processing" bordered={false} key={tag.id}>
                {tag.name}
              </Tag>
            );
          })}
        </Space>
      ),
    },
    {
      title: "发布时间",
      dataIndex: "createdAt",
      key: "createdAt",
      render: (createdAt) => {
        return moment.utc(createdAt).format("YYYY-MM-DD HH:mm:ss");
      },
    },
    {
      title: "操作",
      key: "operation",
      width: 200,
      render: (_, record) => (
        <Space size={[0, 8]}>
          <Button
            type="link"
            icon={<TagsOutlined />}
            onClick={() => showTagModal(record)}
          >
            编辑标签
          </Button>
          <Popconfirm
            title="删除文案"
            description="确定要删除这个文案吗？此操作不可恢复。"
            onConfirm={() => handleDelete(record)}
            okText="确定"
            cancelText="取消"
          >
            <Button type="link" danger icon={<DeleteOutlined />}>
              删除
            </Button>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  const handleSearch = (values: any) => {
    setSearchParams({
      title: values.title || "",
      tagIds: values.tagIds || [],
    });
  };

  const handleReset = () => {
    searchForm.resetFields();
    setSearchParams({
      title: "",
      tagIds: [],
    });
  };

  return (
    <div className="container">
      <Card>
        <Form
          form={searchForm}
          layout="inline"
          onFinish={handleSearch}
          style={{ marginBottom: "16px" }}
        >
          <Form.Item name="title">
            <Input
              placeholder="请输入标题"
              prefix={<SearchOutlined />}
              allowClear
            />
          </Form.Item>
          <Form.Item name="tagIds">
            <Select
              mode="multiple"
              placeholder="请选择标签"
              style={{ width: "200px" }}
              // options={tags.map((tag) => ({ label: tag.name, value: tag.id }))}
              maxTagCount={3}
            />
          </Form.Item>
          <Form.Item>
            <Space>
              <Button type="primary" htmlType="submit">
                搜索
              </Button>
              <Button onClick={handleReset}>重置</Button>
            </Space>
          </Form.Item>
        </Form>

        <Table<ContentData>
          columns={columns}
          dataSource={data}
          rowKey="id"
          loading={loading}
          style={{
            height: `calc(100vh - 260px)`,
            overflow: "auto",
            scrollbarWidth: "none",
          }}
          pagination={{
            current: pagination.page,
            pageSize: pagination.pageSize,
            total: pagination.total,
            showTotal: (total) => `共 ${total} 条`,
            onChange: (page) => fetchContents(page),
          }}
        />

        <Modal
          title="编辑"
          open={isTagModalVisible}
          onOk={handleTagsSave}
          onCancel={handleTagsCancel}
          okText="确定"
          cancelText="取消"
        >
          <div
            style={{ height: 500, overflow: "auto", scrollbarWidth: "none" }}
          >
            <Row style={{ marginBottom: "16px" }}>
              {currentRecord?.attachments.map((o, i) => {
                return (
                  <Col key={i} span={8}>
                    <img
                      src={o.fileUrl}
                      style={{ width: "90%", margin: "3%" }}
                    />
                  </Col>
                );
              })}
            </Row>
            <h3>{currentRecord?.title}</h3>
            <div
              style={{
                whiteSpace: "pre-wrap",
                userSelect: "text",
                backgroundColor: "#f5f5f5",
                padding: "12px",
                borderRadius: "4px",
                fontSize: "14px",
                lineHeight: "1.8",
                cursor: "text",
                transition: "background-color 0.3s",
                border: "1px solid transparent",
                marginBottom: "16px",
              }}
            >
              {currentRecord?.body}
            </div>
            <Form
              form={editTagsForm}
              layout="horizontal"
              labelCol={{ span: 4 }}
              wrapperCol={{ span: 20 }}
            >
              <Form.Item name="recommendReason" label="推荐理由">
                <Input placeholder="请输入推荐理由" />
              </Form.Item>
              <Form.Item
                name="tags"
                label="标签"
                rules={[{ type: "array", max: 5, message: "最多选择5个标签" }]}
              >
                <Select
                  mode="multiple"
                  placeholder="请选择标签"
                  style={{ width: "100%" }}
                  options={tags.map((tag) => ({
                    label: tag.name,
                    value: tag.id,
                  }))}
                  filterOption={false}
                  dropdownRender={(menu) => (
                    <>
                      {menu}
                      <Divider style={{ margin: "8px 0" }} />
                      <Space style={{ padding: "0 8px 4px" }}>
                        <Input
                          placeholder="请输入标签"
                          ref={inputRef}
                          onKeyDown={(e) => e.stopPropagation()}
                          onChange={(e) => setTagname(e.target.value)}
                          value={tagname}
                        />
                        <Button
                          type="text"
                          icon={<PlusOutlined />}
                          onClick={handleCreateTag}
                        >
                          添加标签
                        </Button>
                      </Space>
                    </>
                  )}
                />
              </Form.Item>
            </Form>
          </div>
        </Modal>
      </Card>
    </div>
  );
};

export default ContentPage;
